package com.example.petshopping.network;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.example.petshopping.config.AppConfig;
import com.example.petshopping.model.AppAuthLoginRespVO;
import com.example.petshopping.model.CommonResult;
import com.example.petshopping.model.RefreshTokenRequest;
import com.example.petshopping.ui.login.PhoneLoginActivity;
import com.example.petshopping.utils.TokenManager;
import com.example.petshopping.utils.LocalDateTimeDeserializer;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.time.LocalDateTime;

import java.lang.reflect.Type;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Retrofit客户端
 */
public class RetrofitClient {

    private static final RetrofitClient INSTANCE = new RetrofitClient();
    private final ApiService apiService;
    private static Context appContext;

    private RetrofitClient() {
        // 创建OkHttpClient，添加日志拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .addInterceptor(new HeaderInterceptor())  // 添加请求头拦截器
                .addInterceptor(new ResponseInterceptor())  // 添加响应拦截器
                .build();

        // 创建自定义Gson配置
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeDeserializer())
                .create();

        // 创建Retrofit实例
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(AppConfig.API_BASE_URL)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();

        // 创建API服务
        apiService = retrofit.create(ApiService.class);
    }

    /**
     * 初始化应用上下文
     */
    public static void init(Context context) {
        //通过RetrofitClient的静态上下文变量获取应用程序级别的上下文
        //用于获取accessToken和refreshToken,以及清理token
        appContext = context.getApplicationContext();
    }

    /**
     * 请求头拦截器，用于添加通用请求头
     */
    private static class HeaderInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Request.Builder requestBuilder = originalRequest.newBuilder()
                    .header("tenant-id", "1");

            // 如果有token，添加Authorization头
            if (appContext != null) {
                String token = TokenManager.getToken(appContext);
                if (!TextUtils.isEmpty(token)) {
                    requestBuilder.header("Authorization", "Bearer " + token);
                }
            }

            return chain.proceed(requestBuilder.build());
        }
    }

    /**
     * 响应拦截器，用于处理401错误和自动刷新token
     */
    private static class ResponseInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            // 保留原始请求，用于重新发送
            Request originalRequest = chain.request();
            // 获取响应
            Response response = chain.proceed(originalRequest);

            // 检查是否为401未授权错误
            if (response.code() == 401 && appContext != null) {
                // 获取refreshToken
                String refreshToken = TokenManager.getRefreshToken(appContext);

                if (!TextUtils.isEmpty(refreshToken)) {
                    // 尝试刷新token
                    boolean refreshSuccess = refreshAccessToken(refreshToken);

                    //检查刷新令牌是否成功
                    if (refreshSuccess) {
                        // 刷新成功，重新构建请求
                        response.close(); // 关闭原响应

                        String newToken = TokenManager.getToken(appContext);
                        Request newRequest = originalRequest.newBuilder()
                                .header("Authorization", "Bearer " + newToken)
                                .build();

                        // 重新发送请求（执行）
                        return chain.proceed(newRequest);
                    } else {
                        // 刷新失败，跳转到登录页面
                        redirectToLogin();
                    }
                } else {
                    // 没有refreshToken，跳转到登录页面
                    redirectToLogin();
                }
            }

            return response;
        }

        /**
         * 刷新访问令牌
         */
        private boolean refreshAccessToken(String refreshToken) {
            try {
                // 构建刷新请求
                RefreshTokenRequest refreshRequest = new RefreshTokenRequest(refreshToken);
                //用于序列化和反序列化（对象和json转换），这里的作用是将RefreshTokenRequest 对象转换为 JSON 字符串以便发送网络请求。
                Gson gson = new Gson();
                String jsonBody = gson.toJson(refreshRequest);
                // 创建请求体
                RequestBody requestBody = RequestBody.create(
                        jsonBody,
                        // 指定请求体的媒体类型
                        MediaType.parse("application/json")
                );
                // 创建请求
                Request request = new Request.Builder()
                        .url(AppConfig.API_BASE_URL + "member/auth/refresh-token")
                        .post(requestBody)
                        .header("Content-Type", "application/json")
                        .header("tenant-id", "1")
                        .build();

                // 创建新的OkHttpClient，防止使用原来的Client重新发送请求的时候还会使用过期的accessToken从而造成拦截器循环
                OkHttpClient simpleClient = new OkHttpClient();
                Response response = simpleClient.newCall(request).execute();

                if (response.isSuccessful() && response.body() != null) {
                    String responseBody = response.body().string();

                    // 使用TypeToken正确解析泛型类型
                    Type type = new TypeToken<CommonResult<AppAuthLoginRespVO>>() {
                    }.getType();
                    CommonResult<AppAuthLoginRespVO> result = gson.fromJson(responseBody, type);

                    if (result.isSuccess() && result.getData() != null) {
                        AppAuthLoginRespVO data = result.getData();

                        // 保存新的token
                        TokenManager.saveToken(appContext, data.getAccessToken());
                        TokenManager.saveRefreshToken(appContext, data.getRefreshToken());
                        TokenManager.saveUserId(appContext, data.getUserId());

                        return true;
                    }
                }
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }

        /**
         * 跳转到登录页面
         */
        private void redirectToLogin() {
            if (appContext != null) {
                // 清除所有token
                TokenManager.logout(appContext);

                // 跳转到登录页面
                Intent intent = new Intent(appContext, PhoneLoginActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                appContext.startActivity(intent);
            }
        }
    }

    public static RetrofitClient getInstance() {
        return INSTANCE;
    }

    public ApiService getApiService() {
        return apiService;
    }
} 